#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import random
import time

import pygame
import yaml

import const
from musicPlay import Game, Combo, Decorate, Score


def initConfig():
	file = open('./defines.yaml', 'r')
	const.Configs = yaml.load(file, Loader=yaml.FullLoader)
	print("-" * 30 + "\n")
	for k, v in const.Configs.items():
		if type(v) in (tuple, list):
			for i, vv in enumerate(v):
				print("%s[%s]: %s\n" % (k, i, vv))
		elif isinstance(v, dict):
			for kk, vv in const.Configs.items():
				print("{%s: %s}: %s\n" % (k, kk, vv))
		else:
			print("%s: %s\n" % (k, v))
	print("-" * 30 + "\n\n")


def initSrc():
	# 音符圆圈资源 初始化
	for d in const.CircleFileRange:
		circleDir = const.Configs['circlePath'] % d
		circleNames = os.listdir(circleDir)
		musicCircles = []
		for name in circleNames:
			musicCircles.append(pygame.image.load(circleDir + name).convert_alpha())
		const.MusicCircleList.append(musicCircles)

	# 乐谱谱面
	with open(const.Configs['file']['play'], 'r', encoding='utf8') as f:
		for i in f.readlines():
			nodes = i.strip().split(' ')
			if len(nodes) < 2:
				continue
			speed = const.NodeSpeed
			if not speed:
				speed = random.uniform(1.2, 2)

			nodes[1] = float(nodes[1]) - speed
			if float(nodes[1]) < 0:
				speed = speed - float(nodes[1])
				nodes[1] = 0
			nodes.append(speed)
			const.MusicNodeList.append(nodes)
	sorted(const.MusicNodeList, key=lambda n: n[1])

	# 分数资源
	for i in range(10):
		numImg = pygame.image.load(const.Configs['file']['number'] % i)
		const.MusicNumberList.append(numImg)

	# slider资源
	sliderFiles = os.listdir(const.Configs['sliderPath'])
	sorted(sliderFiles, key=lambda item: int(item[19:-4]))
	for slider in sliderFiles:
		const.MusicSliderList.append(pygame.image.load(const.Configs['sliderPath'] + slider))

	# hit资源
	hitFiles = os.listdir(const.Configs['hitPath'])
	sorted(hitFiles)
	for hit in hitFiles:
		const.MusicHitList.append(pygame.image.load(const.Configs['hitPath'] + hit))

	# score资源
	for i, score in enumerate(const.Scores):
		const.MusicScoreMap[score] = pygame.image.load(const.Configs['scorePath'] + str(i)+'.png')

	# 摁键处理
	keys = [pygame.K_a, pygame.K_w, pygame.K_d, pygame.K_s, pygame.K_LEFT, pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN]
	for i, key in enumerate(keys):
		if i < 4:
			const.KeyMaps[key] = str(i+1)
		else:
			const.KeyMaps[key] = str(i-3) if const.GameModel == 1 else str(i+2)


def GameMain():
	initConfig()

	# 使用pygame之前必须初始化
	pygame.init()
	# 设置主屏窗口
	screen = pygame.display.set_mode([const.Width, const.Height])
	# 设置窗口的标题，即游戏名称
	pygame.display.set_caption("music game")

	# 中心区域
	fixImg = pygame.image.load(const.Configs['file']['fixImg'])
	rect = fixImg.get_rect()
	rect.center = (const.RectWidth, const.RectHeight)

	# 背景
	bgImgSrc = const.Configs['bgImgPath'] + random.choice(os.listdir(const.Configs['bgImgPath']))
	bgImg = pygame.image.load(bgImgSrc)
	bgRect = bgImg.get_rect()
	bgRect.center = (const.BgRectWidth, const.BgRectHeight)

	# 音乐
	pygame.mixer.init()
	pygame.mixer.music.load(const.Configs['file']['music'])
	pygame.mixer.music.play(1, 0)

	# 帧数
	clock = pygame.time.Clock()
	clock.tick(const.Fps)

	# 初始化 玩法资源
	initSrc()

	# 游戏开始时间
	const.StartTime = time.time()

	# 实例化
	showScore = Score(screen)
	combo = Combo(screen)
	decorate = Decorate(screen)
	game = Game(screen, showScore, combo, decorate)

	while True:
		screen.fill((0, 0, 0))
		screen.blit(bgImg, bgRect)
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				# 卸载所有模块
				pygame.quit()
				exit()
			elif event.type == pygame.KEYDOWN:
				game.manualPress(event.key)
		if const.GameAuto:
			game.autoPress()

		screen.blit(fixImg, rect)

		decorate.update()
		game.addShows()
		game.update()
		showScore.update()
		combo.update()

		clock.tick(const.Fps)

		# 更新屏幕内容
		pygame.display.flip()


if __name__ == "__main__":
	GameMain()
